﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using LigerMVC.Common.Expressions;
using LigerMVC.Common.JSON;

namespace LigerMVC.Common.MVC
{
    /// <summary>
    /// 处理分页排序的信息
    /// </summary>
    public class QuerySimpleDescriptorBinder : IModelBinder
    {
        protected HttpRequestBase _request;
          
        public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        { 
            _request = controllerContext.HttpContext.Request;

            var descriptor = new QuerySimpleDescriptor 
            { 
                PageIndex = 1 , 
                Condition=new List<QueryCondition>()
            };
            var provider = controllerContext.Controller.ValueProvider;
            

            //排序
            var sortname = GetRequestValue("sortname");
            var sortorder = GetRequestValue("sortorder");
            if (sortname != null)
            {
                descriptor.OrderBy = new OrderByClause
                {
                    Key = sortname,
                    Order = sortorder == null || sortorder.ToLower() == "asc" ? 
                        OrderSequence.ASC : OrderSequence.DESC
                };
            } 

            //分页
            descriptor.PageIndex = GetRequestValue("page").ToInt();
            descriptor.PageSize = GetRequestValue("pagesize").ToInt();

            //条件
            var queryWhere = GetRequestValue("where");
            var queryCondition = GetRequestValue("condition");
            if (!string.IsNullOrEmpty(queryWhere))
            {
                var filterGroup = JSONHelper.FromJson<FilterGroup>(queryWhere);
                descriptor.LoadCondition(filterGroup);
            }
            else if (!string.IsNullOrEmpty(queryCondition))
            {
                var filterRules = JSONHelper.FromJson<IList<FilterRule>>(queryCondition);
                descriptor.LoadCondition(new FilterGroup
                {
                    op = "and",
                    rules = filterRules
                });
            }
            return descriptor;
        }

        protected string GetRequestValue(string key)
        {
            if (_request.HttpMethod.ToUpper() == "POST")
                return _request.Form[key];

            return _request.QueryString[key];
        } 
    } 
}